package com.zzj.ecology.framework.configs.security;

import com.alibaba.fastjson.JSON;
import com.zzj.ecology.common.enums.LoginResultEnum;
import com.zzj.ecology.system.dto.HttpResult;
import org.springframework.http.MediaType;
import org.springframework.security.web.session.SessionInformationExpiredEvent;
import org.springframework.security.web.session.SessionInformationExpiredStrategy;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 当账号异地登录导致被挤下线时也要返回给前端json格式的数据.
 * 比如提示"账号下线"、"您的账号在异地登录，是否是您自己操作"或者"您的账号在异地登录,
 * 可能由于密码泄露，建议修改密码"等。
 * 这时就要实现SessionInformationExpiredStrategy（会话信息过期策略）来自定义会话过期时的处理逻辑
 */

/**
 * @ClassName CustomizeSessionInformationExpiredStrategy
 * @Description TODO
 * @Author zhijun zeng at 2020/2/29
 * @Version 1.0
 **/
@Component
public class CustomizeSessionInformationExpiredStrategy implements SessionInformationExpiredStrategy {

    @Override
    public void onExpiredSessionDetected(SessionInformationExpiredEvent sessionInformationExpiredEvent) throws IOException, ServletException {

        HttpServletResponse resp = sessionInformationExpiredEvent.getResponse();
        resp.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        LoginResultEnum others = LoginResultEnum.USER_ACCOUNT_USE_BY_OTHERS;
        resp.getWriter().write(JSON.toJSONString(new HttpResult(others.getCode(),others.getName())));
    }
}
